#pragma once

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <string.h>
#include "log.hpp"

const char *pathname = "/home/zs";
const int proj_id = 0x2303;

struct msgbuffer
{
    long type;
    char body[1024];
};

class Init
{
public:
    Init()
    {
        key = ftok(pathname, proj_id);
        if (key < 0)
        {
            logbook(Fatal, "ftok error: %s", strerror(errno));
            _exit(1);
        }
        // 创建消息队列
        msgid = msgget(key, IPC_CREAT | 0777);
        if (msgid < 0)
        {
            logbook(Fatal, "msgget error: %s", strerror(errno));
            _exit(1);
        }

        system("ipcs -q");
    }
    ~Init()
    {
        msqid_ds buf;
        if (msgctl(msgid, IPC_STAT, &buf) != -1)
        {
            if (errno != EINVAL)
            {
                // 删除消息队列
                if (msgctl(msgid, IPC_RMID, nullptr) < 0)
                {
                    logbook(Fatal, "msgctl error: %s", strerror(errno));
                    _exit(1);
                }
                std::cout << "删除消息队列成功" << std::endl;
            }
        }
        system("ipcs -q");
    }

    int Getid()
    {
        return msgid;
    }

private:
    key_t key;
    int msgid;
};
Init msg;
